package net.lanelife.casino.cms.web.controller;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import net.lanelife.casino.caipiao.dto.admin.CrawlerConfigCreateDTO;
import net.lanelife.casino.caipiao.dto.admin.CrawlerConfigDTO;
import net.lanelife.casino.caipiao.dto.admin.CrawlerConfigTable;
import net.lanelife.casino.caipiao.dto.admin.CrawlerConfigUpdateDTO;
import net.lanelife.casino.caipiao.entity.CrawlerConfig;
import net.lanelife.casino.caipiao.service.api.ICrawlerConfigService;
import net.lanelife.casino.caipiao.service.api.IGameTypeService;
import net.lanelife.casino.cms.web.controller.support.CRUDController;
import net.lanelife.casino.common.service.support.IGenericService;
import net.lanelife.casino.common.web.resolver.MessageResolver;
import net.lanelife.casino.common.web.resolver.ViewResolver;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.collect.Lists;

@Controller
@RequestMapping(value = CrawlerConfigController.PATH)
public class CrawlerConfigController extends CRUDController<CrawlerConfig, Integer, CrawlerConfigDTO, CrawlerConfigCreateDTO, CrawlerConfigUpdateDTO, CrawlerConfigTable<CrawlerConfigDTO>> {
	
	public static final String PATH = "/crawler-config";
	
	public CrawlerConfigController() {
		super(PATH);
	}
	
	@Autowired
	private ICrawlerConfigService crawlerConfigService;

	@Autowired
	private IGameTypeService gameTypeService;
	
	@Override
	protected IGenericService<CrawlerConfig, Integer> getService() {
		return crawlerConfigService;
	}
	
	@Override
	protected void preList(Model model, ServletRequest request) throws Exception {
		model.addAttribute("gameList", gameTypeService.findAll());
	}
	
	@Override
	protected void preCreate(Model model, CrawlerConfigCreateDTO createDTO) throws Exception {
		model.addAttribute("gameList", gameTypeService.findAll());
	}
	
	@Override
	@RequestMapping(value = { "/create" }, method = RequestMethod.POST)
	public String create(Model model, @Valid @ModelAttribute CrawlerConfigCreateDTO createDTO, BindingResult br, ServletRequest request) throws Exception {
		if (!br.hasErrors()) {
			if (request.getParameter("test").equals("true")) {
				//Request req = Request.Get(uri)
				String[] groupIndexs = createDTO.getGroupIndexs().split("\\|", -1);
				StringBuilder result = new StringBuilder();
				HttpClient client = HttpClientBuilder.create().build();
				HttpGet get = new HttpGet(createDTO.getUrl());
				get.addHeader("Referer", "http://www.lecai.com/lottery/cqssc/");
				HttpResponse resp = client.execute(get);
				if (resp.getStatusLine().getStatusCode() == 200) {
					String content = EntityUtils.toString(resp.getEntity(), "UTF-8");
					Pattern pattern = Pattern.compile(createDTO.getExpression());
					Matcher matcher = pattern.matcher(content);
					if (matcher.find()) {
						result.append("匹配项:\r\n");
						for (int i = 1; i <= matcher.groupCount(); i++) {
							result.append("　");
							result.append(MessageResolver.getMessage("crawlerconfig.test.index"));
							result.append(i);
							result.append(":　");
							result.append(matcher.group(i)).append("\r\n");
						}
						result.append("开奖号码:　");
						try {
							for (String index : groupIndexs) {
								result.append(matcher.group(Integer.valueOf(index))).append(",");
							}
							result.deleteCharAt(result.length() - 1);
						} catch (Exception e) {
							result.append(MessageResolver.getMessage("crawlerconfig.exception.IndexException")); // 号码索引错误
						}
					} else {
						result.append(MessageResolver.getMessage("crawlerconfig.exception.NoMatchesException")); // 未发现匹配项
					}
				} else {
					result.append(MessageResolver.getMessage("crawlerconfig.exception.HttpStatusException")); // 抓取网页内容失败
				}
				model.addAttribute("result", result.toString());
				return ViewResolver.getView(PATH + "/create");
			}
		}
		return super.create(model, createDTO, br, request);
	}

	@Override
	protected void preUpdate(Model model, CrawlerConfigUpdateDTO updateDTO) throws Exception {
		model.addAttribute("gameList", gameTypeService.findAll());
	}
	
	@RequestMapping(value = { "/available:{available}/{id}" }, method = RequestMethod.GET)
	public String available(@PathVariable Integer id, @PathVariable Boolean available) throws Exception {
		crawlerConfigService.update(id, available);
		return ViewResolver.getView(PATH + "/list");
	}

}
